package com.taobao.shopcart.api;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.taobao.base.model.RestResponse;
import com.taobao.shopcart.mapper.OrdersMapper;
import com.taobao.shopcart.model.po.Orders;
import com.taobao.utile.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin

public class PayController {


    @Autowired
    private PayUtil payUtil;
    @Autowired
    private OrdersMapper ordersMapper;


    @ResponseBody
    @GetMapping("/pay/{orderId}")
    public RestResponse<String> alipay(@PathVariable("orderId") long orderId) throws AlipayApiException, InterruptedException {

        System.out.println(orderId);
        Orders orders = ordersMapper.selectByOrderId(orderId);

        // 生成订单号
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        // 调orderService 确认order todo:

        String s = payUtil.sendRequestToAlipay(String.valueOf(orderId), orders.getTotalAmount(), orders.getNote());
        return RestResponse.success(s);
    }

    // 支付完成后跳转到这个接口
    @PostMapping("/paySuccess")
    public String paySuccess(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (String key : parameterMap.keySet()) {
            String[] values = parameterMap.get(key);
            String valueStr = String.join(",", values); // 处理数组参数
            params.put(key, valueStr);
        }

        String query = payUtil.query(params.get("out_trade_no"));

        System.out.println("===>" + query);
        JSONObject jsonObject = JSONObject.parseObject(query);
        Object o = jsonObject.get("alipay_trade_query_response");
        Map map = (Map) o;
        System.out.println(map);
        Object s = map.get("trade_status");
        if (s.equals("TRADE_SUCCESS")) {
            System.out.println("支付成功");

            System.out.println(s);
            return "redirect:http://localhost:47741/sdf";
        }else{
        System.out.println("支付失败");
        return "redirect:http://localhost:47741/sdf";
        }
    }

}
